// pages/chart/chart.js
var wxCharts = require('../../utils/wxcharts.js')
var Util = require('../../utils/util.js')
const db = wx.cloud.database()
const _ = db.command
var app = getApp();
var pieChartPayment = null;
var pieChartIncome = null;
var columnChartWeek = null;
var columnChartMonth = null;

var chartDataWeek = {
  title: '周趋势',
  data: [35, 20, 45, 37, 0, 10],
  categories: ['09/13-9/19', '09/20-09/26', '09/27-10/03', '10/04-10/10', '10/11-10/17', '10/18-10/24']
}
var chartDataMonth = {
  title: '月趋势',
  data: [0, 0, 0, 0, 100, 47],
  categories: ['5月', '6月', '7月', '8月', '9月', '10月']
}

Page({
  data: {
    tabs: ["总览", "支出", "收入", "周趋势", "月趋势"],
    tabsData: [0, 0, 0, 0],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    billData: null,

    incomeList: [{
      name: '未知',
      data: 1
    }]
  },

  tabChange: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  bindBillClick: function(e) {
    console.log(e.currentTarget.dataset)
    let id = e.currentTarget.dataset.bill._id;
    let openid = e.currentTarget.dataset.bill.openid;
    let type = e.currentTarget.dataset.bill.type;
    let account = e.currentTarget.dataset.bill.account;
    let desc = e.currentTarget.dataset.bill.desc;
    let datetime = e.currentTarget.dataset.bill.datetime;
    let cate = e.currentTarget.dataset.bill.cate;
    let amount = e.currentTarget.dataset.bill.amount;
    let account1 = e.currentTarget.dataset.bill.account1;
    let account2 = e.currentTarget.dataset.bill.account2;
    if (type == '支出' || type == '收入') {
      wx.navigateTo({
        url: 'billdetail?id=' + id + '&openid=' + openid + '&type=' + type + '&account=' + account + '&desc=' + desc + '&datetime=' + datetime + '&cate=' + cate + '&amount=' + amount
      })
    }
    else {
      wx.navigateTo({
        url: 'billdetail?id=' + id + '&openid=' + openid + '&type=' + type + '&account1=' + account1 + '&account2=' + account2 + '&desc=' + desc + '&datetime=' + datetime + '&amount=' + amount
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (getCurrentPages().length != 0) {

      //刷新当前页面的数据

      getCurrentPages()[getCurrentPages().length - 1].onLoad()

    }
  },

  // 字符串转日期
  stringToDate: function(dateStr, separator){
    if(!separator) {
      separator = "-";
    }
    let dateArr = dateStr.split(separator);
    let year = parseInt(dateArr[0]);
    let month;                       
    if(dateArr[1].indexOf("0") == 0) {
      month = parseInt(dateArr[1].substring(1));
    }
    else {
      month = parseInt(dateArr[1]);
    }
    let day = parseInt(dateArr[2]);
    let date = new Date(year, month - 1, day);
    return date;
  },

  onLoad: function(e) {
    var that = this

    this.setData({
      
    })

    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        this.setData({
          openid: res.result.openid,
        })
        db.collection("user_bill").where({_openid: this.data.openid}).get()
        .then(res => {
          this.setData({
            billData: res.data.reverse()
          })
          // 按类型分类
          db.collection("user_bill").aggregate().match({
            _openid: that.data.openid
          }).group({
            _id: '$type',
            sum: _.aggregate.sum('$amount')
          }).end().then(function(res) {
            that.setData({
              totalList: res.list
            })
            let _tabsData = [0, 0, 0, 0]
            for (let i = 0; i < that.data.totalList.length; i++) {
              if (that.data.totalList[i]._id == '支出') {
                _tabsData[0] = that.data.totalList[i].sum
              }
              else if (that.data.totalList[i]._id == '收入') {
                _tabsData[1] = that.data.totalList[i].sum
              }
              else if (that.data.totalList[i]._id == '转账') {
                _tabsData[2] = that.data.totalList[i].sum
              }
              else if (that.data.totalList[i]._id == '还款') {
                _tabsData[3] = that.data.totalList[i].sum
              }
              that.setData({
                tabsData: _tabsData
              })
            }
            console.log(that.data.totalList)
          })

          // 按支出分类
          db.collection("user_bill")
          .aggregate().match({
            _openid: that.data.openid,
            type: '支出'
          }).group({
            _id: '$cate',
            sum: _.aggregate.sum('$amount')
          }).end().then(function(res) {
            that.setData({
              paymentList: res.list
            })
            console.log(that.data.paymentList)
            function renameKey(obj, old_key, new_key) {
              if (old_key != new_key) {
                Object.defineProperty(obj, new_key, Object.getOwnPropertyDescriptor(obj, old_key));
              }
              delete obj[old_key]
            }
            that.data.paymentList.forEach(obj => renameKey(obj, '_id', 'name'))
            that.data.paymentList.forEach(obj => renameKey(obj, 'sum', 'data'))
            if (that.data.paymentList.length != 0) {
              pieChartPayment = new wxCharts({
                animation: true,
                canvasId: 'pieCanvasPayment',
                type: 'pie',
                series: that.data.paymentList,
                width: windowWidth,
                height: 300,
                dataLabel: true,
              });
            }
          })

          // 按收入分类
          db.collection("user_bill")
          .aggregate().match({
            _openid: that.data.openid,
            type: '收入'
          }).group({
            _id: '$cate',
            sum: _.aggregate.sum('$amount')
          }).end().then(function(res) {
            that.setData({
              incomeList: res.list
            })
            function renameKey(obj, old_key, new_key) {
              if (old_key != new_key) {
                Object.defineProperty(obj, new_key, Object.getOwnPropertyDescriptor(obj, old_key));
              }
              delete obj[old_key]
            }
            that.data.incomeList.forEach(obj => renameKey(obj, '_id', 'name'))
            that.data.incomeList.forEach(obj => renameKey(obj, 'sum', 'data'))
            if (that.data.incomeList.length != 0) {
              pieChartIncome = new wxCharts({
                animation: true,
                canvasId: 'pieCanvasIncome',
                type: 'pie',
                series: that.data.incomeList,
                width: windowWidth,
                height: 300,
                dataLabel: true,
              });
            }
          })
        })
        .catch(err => {
          console.log(err)
        })

      }
    })

    wx.setNavigationBarTitle({
      title: '统计',
    })

    var windowWidth = 320;

    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch(e) {
      console.error('getSystemInfoSync failed!');
    }

    let currentDate = Util.getCurrentDate()
    console.log(this.stringToDate(currentDate))
    var that = this
    db.collection('user_bill').where({
      _openid: this.data.openid,
      datetime: _.lte(this.stringToDate(currentDate) + 24 * 60 * 60)
    }).get({success: res => {
        console.log(res.data)
      }
    })

    columnChartWeek = new wxCharts({
      canvasId: 'columnCanvasWeek',
      type: 'column',
      animation: true,
      categories: chartDataWeek.categories,
      series: [{
        name: '消费总额度',
        data: chartDataWeek.data,
        format: function (val, name) {
          return val.toFixed(2) + '元';
        }
      }],
      yAxis: {
        format: function (val) {
          return val + '元';
        },
        min: 0
      },
      xAxis: {
        disableGrid: false,
        type: 'calibration'
      },
      extra: {
        column: {
          width: 15
        }
      },
      width: windowWidth,
      height: 200,
    });

    columnChartMonth = new wxCharts({
      canvasId: 'columnCanvasMonth',
      type: 'column',
      animation: true,
      categories: chartDataMonth.categories,
      series: [{
        name: '消费总额度',
        data: chartDataMonth.data,
        format: function (val, name) {
          return val.toFixed(2) + '元';
        }
      }],
      yAxis: {
        format: function (val) {
          return val + '元';
        },
        min: 0
      },
      xAxis: {
        disableGrid: false,
        type: 'calibration'
      },
      extra: {
        column: {
          width: 15
        }
      },
      width: windowWidth,
      height: 200,
    });
  }
})